
import api from '../../../api/index';
// dietaryRecommendations/pages/enterfoodlist/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    pageNum: 0,
		pageSize: 40,
    totalKcal: 0,
    curDate: null,
    name: '',
    show: false,
    carl: 0,
    curList:[],
    foodList: [],
    foodDetail: {},
    addList: [],
    showpopup: false,
    confirmFoodsBefore: (action) => {
        const _this = this
        return new Promise((resolve) => {
            if (action === 'confirm') {
                // const pages = getCurrentPages()
                // let page = pages[pages.length-1]
                // console.log(page.data.foodDetail);
                const amount = foodDetail.inputamount
                if(!amount || amount == 0) {
                    wx.showToast({
                        title: '请填写数量',
                        icon: 'none',
                        duration: 1000
                    })
                    resolve(false);
                } else {
                    resolve(true);
                }
            resolve(true);
            } else {
            // 拦截取消操作
            resolve(true);
            }
        })
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var { curDate, time } = options
    if (curDate) {
      this.setData({
        curDate,
        curtime: time
      })
    } 
    this.getlist()
  },
  confirmFoods() {
    console.log(this.data.foodDetail);
    let foodDetail = this.data.foodDetail
    foodDetail.food = [this.data.foodDetail.id,this.data.foodDetail.name]
    foodDetail.date = this.data.curDate
    foodDetail.time = this.data.curtime
    let amount = foodDetail.inputamount
    if(!amount || amount == 0) {
        wx.showToast({
            title: '请填写数量',
            icon: 'none',
            duration: 1000
        })
    } else {
      foodDetail.sandamount = foodDetail.amount*foodDetail.inputamount
      
      this.setData({
        carl: 0
    })
      this.data.addList.push(foodDetail)
      let totalKcal = 0;
        for (let i = 0; i < this.data.addList.length; i++) {
          totalKcal += parseFloat(this.data.addList[i].carl);
        }
        this.setData({
          totalKcal: totalKcal.toFixed(3)
        })
        console.log(totalKcal);
        console.log('ketyi',this.data.addList);
    }
    // wx.showToast({
    //     title: '开发中。。。。',
    //     icon: 'none',
    //     duration: 1000
    // })
  },
  bindInput(e) {
      const val = e.detail.value;
    this.setData({
        'foodDetail.inputamount': val
    })
    console.log(val);
    console.log(this.data.foodDetail);
    console.log(this.data.carl);
    let fooddata = this.data.foodDetail
    console.log(fooddata);
    fooddata.inputamount = parseFloat(fooddata.inputamount)
    fooddata.kcal = parseFloat(fooddata.kcal)
    console.log(fooddata.kcal);
    fooddata.carl = fooddata.amount/100 * fooddata.kcal*fooddata.inputamount
    this.setData({
      carl: fooddata.carl?fooddata.carl:0,
      foodDetail: fooddata
  })
  console.log(this.data.foodDetail);
  },

  toJson(str) {
    try {
        return JSON.parse(str)
    }catch(e) {
        return []
    }
},
  addFood(e) {
    const index = e.currentTarget.dataset.index
    const detail = this.data.foodList[index]
    console.log(this.data.foodList);
    console.log(detail);
    detail.foodIndex = index
    detail.inputunit = detail.units[0].unit
    detail.amount = detail.units[0].amount
    this.setData({
      carl: detail.carl?detail.carl: 0,
        foodDetail: detail,
        show: true
    })
  },
  doSelSportItem(e) {
    // const index = e.currentTarget.dataset.index
    let targetId = e.currentTarget.dataset.id
    console.log(targetId);
    console.log(this.data.addList);
    let index = this.data.addList.findIndex(item => item.id === targetId);
    let detail = this.data.addList[index]
    console.log(detail);
    this.setData({
        carl: detail.carl?detail.carl: 0,
        foodDetail: detail,
        show: true
    })
  },
  deletell(e) {
    this.setData({
      totalKcal: ''
    })
    console.log(e);
    let index = e.currentTarget.dataset.index
    let data = this.data.addList
    data.splice(index, 1);
    console.log(data);
    this.setData({
      addList: data
    })
    if(data.length>0) {
      let totalKcal = 0;
        for (let i = 0; i < data.length; i++) {
          totalKcal += parseFloat(data[i].carl);
        }
        this.setData({
          totalKcal: totalKcal.toFixed(3)
        })
        console.log(totalKcal);
    } else {
      this.setData({
        totalKcal: ''
      })
    }
    
},
	onChangeshop(e) {
		this.setData({
			name: e.detail
		});
    this.onSearch()
	},
	onSearch() {
        this.setData({
          foodList: [],
          pageNum: 0,
			    pageSize: 40,
		    });
        console.log('搜索' + this.data.name);
        this.getlist()
    },
    onCancelSearch() {
      this.setData({
        foodList: [],
        pageNum: 0,
        pageSize: 40
      });
        this.getlist()
      },
    changeUnt(e){
        const index = e.currentTarget.dataset.index
        console.log(index);
        const detail = this.data.foodDetail
        detail.inputunit = detail.units[index].unit
        detail.amount = detail.units[index].amount
        console.log(detail);
        detail.carl = detail.amount/100*detail.kcal*detail.inputamount
        console.log(detail.carl);
        
        
        detail.units.forEach((el, ind) => {
            el.checked = index == ind
        })
        this.setData({
            carl: detail.carl?detail.carl:0,
            foodDetail: detail
        })
        console.log(this.data.foodDetail);
    },
    getlist() {
        api.post('/api/hxhealth/datetimefood/dict/list', {
          head: {
            firstresult: this.data.pageNum,
            maxresults: this.data.pageSize,
            bodytype: 'flat',
          },
                data: {
                    name: this.data.name
                }
            })
            .then((res) => {
              if (res.length == 0) { //请求的数据为空，没有数据
                if (this.data.pageNum == 0) { // 第一页都没有数据，直接显示暂无数据
                  this.setData({
                    noData: true,
                  })
                } else { // 不为第一页时，请求的数据为空，说明没有更多数据了，把pageNum减一，是为了下次触底可以继续请求刷新，万一有了新数据也可以正常显示出来
                  this.setData({
                    noMor: true,
                    pageNum: 0
                  })
                }
              } else {
                console.log('====================================');
                console.log('sousuo',this.data.name);
                console.log('====================================');
                res?.forEach(el => {
                  el.units = this.toJson(el.units)
                  if(el.units?.[0]) {
                      el.units[0].checked = true
                  }
              })
                const dataList = [...this.data.foodList, ...res]
                
                if (res.length == this.data.pageSize) { // 请求的数据为10条，说明下一页可能还有数据，列表添加上新的数据，把其他状态设为不显示
                  this.setData({
                    foodList: dataList,
                    noMor: false,
                    noData: false
                  })
                } else { // 请求的数据没有10条，说明下一页已经暂时没有数据了，列表添加上新的数据，底部显示暂无更多数据
                  console.log('====================================');
                  console.log(res.length,this.data.pageSize);
                  console.log(res);
                  console.log('====================================');
                  this.setData({
                    foodList: dataList,
                    noMor: true,
                    noData: false
                  })
                }
                console.log(this.data.foodList);
                // this.setData({
                //     'foodList': dataList || [],
                // });
              }
            })
            .catch((e) => {
                console.log('error', e);
            });
    },
    showPopup() {
        console.log('弹出',this.data.addList);
        this.setData({
          addList: this.data.addList
        })
        this.setData({ showpopup: true });
        // if(this.data.addList.length>0) {
        //   this.setData({ showpopup: true });
        // } else {
        //   // wx.showToast({
        //   //   icon: 'none',
        //   //   title: '请输入运动时间'
        //   // });
        // }
        
      },
    
      onClose() {
        this.setData({ showpopup: false });
      },
      svaeItem() {
        console.log(this.data.curDate);
        const data = this.data.addList
        console.log(data);
        if(data.length == 0) {
             wx.showToast({
            icon: 'none',
            title: '请添加菜品'
          });
        }
        let updatedData = data.map(item => {
          const { id, ...rest } = item;
          return rest;
        });
        
        console.log(updatedData);
        
        for (let i = 0; i < updatedData.length; i++) {
          updatedData[0].kcal = updatedData[0].carl
          
        }
        console.log(updatedData);
        api.post('/api/hxhealth/datetimefood/save', {
          data: updatedData
      }).then(res => {
          console.log(res);
          this.onClose()
          wx.navigateBack({
            delta: 1 //返回的页面数，如果 delta 大于现有页面数，则返回到首页,
          });
          // wx.navigateTo({ url: `/dietaryRecommendations/pages/enterfood/index?curDate=${this.data.dd}` });
      }).catch(e => {
          console.log(e)
      })
      },
      godetailsPage(e) {
        console.log(e);
        let id = e.currentTarget.dataset.id
        wx.navigateTo({ url: `/dietaryRecommendations/pages/fooddetails/index?id=${id}` });
      },
      delete(e) {
        console.log(e.currentTarget.dataset.id);
          let id = e.currentTarget.dataset.id
        var that = this
        Dialog.confirm({
          title: '删除',
          message: '确定要删除吗？',
        })
          .then(() => {
            console.log('2222');
            that.setData({
              itemData: [],
              totalKcal: 0
            })
            try {
              api.get(`/api/hxhealth/datetimefood/remove/${id}`).then((res) => {
                console.log(res);
                console.log('重新获取当前餐情况');
              });
            } catch (e) {
              console.error(e);
            }
          })
          .catch(() => {
            // on cancel
            console.log('333');
          });
    
      },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.setData({
      foodList: [],
      noMor: false,
      noData: false,
			pageNum: 0,
			pageSize: 40,
		});
    this.getlist();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    console.log('到底了--------');
    if ((this.data.pageNum + 1) * this.data.pageSize == this.data.foodList.length) { 
      // 数据列表的数量刚好等于页数*每页条数，可以请求下一页
        this.setData({
          pageNum: this.data.pageNum + 1, // 一般上拉触底是为了加载更多分页数据，所以这里页数自增
        });
        // 查询列表方法
        this.getlist(); 
      } else { 
      // 数据列表的数量不等于页数*每页条数，说明当前页数据不足10条，已经没有更多数据了
        this.setData({
          noMor: true  // 这里在页面最底部显示一排文字，没有更多数据了
        })
      }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})